export default {
  getData,
  setData,
  emit, //设置子组件传递page页
  getParam, //获取点击时间参数
  routePush,//路由跳转
  navigateBack,
  previewImage,
  getImageInfo,
  saveImageToPhotosAlbum,
  setKeepScreenOn, //设置屏幕常亮
  setStorageSync, //设置同步缓存
  getStorageSync, //获取同步缓存
  removeStorageSync, //移除同步缓存
  setStorage,//设置缓存
  getStorage,//获取缓存
  removeStorage,//移除缓存
  showToast, //消息提示框
  showModal, //模态对话框
  scanCode, //扫一扫
  login, //调用接口获取登录凭证（code）
  getUserInfo,//获取用户信息
  getLocation, //获取经纬度
  openSetting,
  checkPhone, //手机号正则匹配
  time,
}

/**
 * 获取data值
 * that 作用域
 * key 需要获取值的key
 */
function getData(that, key) {
  let value = null;
  try {
    value = that.data[key];
  } catch (e) {
    console.error("getData错误");
  }
  return value;
}

/**
 * 设置data值
 * that 作用域
 * valueObj [Object] 需要设置到data的所有值
 * callback setData引起的界面更新渲染完毕后的回调函数
 */
function setData(that, valueObj, callback) {
  try {
    that.setData(valueObj, function() {
      if (callback) callback();
    })
  } catch (e) {
    console.error("setData错误");
  }
}

/**
 * 子组件传递数据到父组件
 * that 作用域
 * key  传递中间key
 * vakue  传递值
 */
function emit(that, key, value) {
  try {
    that.triggerEvent(key, value);
  } catch (e) {
    console.error("子组件传递数据到父组件错误");
  }
}

/**
 * 获取页面点击事件参数
 * event 事件参数
 * key 需要获取的key
 */
function getParam(event, key) {
  let value = null;
  try {
    value = event.currentTarget.dataset[key];
  } catch (e) {
    console.error("点击事件参数获取失败错误");
  }
  return value;
}

// navigate	对应 wx.navigateTo 或 wx.navigateToMiniProgram 的功能
// redirect	对应 wx.redirectTo 的功能
// switchTab	对应 wx.switchTab 的功能
// reLaunch	对应 wx.reLaunch 的功能	1.1.0
function routePush(url, type = "navigate"){
  try{
    if (type =="switchTab"){
      // 不可携带参数
      wx.switchTab({ url })
    } else if (type == "reLaunch") {
      wx.reLaunch({ url })
    } else if (type == "redirectTo") {
      wx.redirect({ url })
    } else {
      wx.navigateTo({ url })
    }
  }catch(e){
    console.error(`wx.${type} API错误`);
  }
}

function navigateBack(delta = 1){
  try{
    wx.navigateBack({
      delta
    })
  }catch(e){
    console.error(" wx.navigateBack API错误");
  }
}

// 全屏预览图片
function previewImage(url) {
  try{
    if(!url) return;
    wx.previewImage({
      current: url,
      urls: [url],
    })
  }catch(e){
    console.error(" wx.previewImage API错误");
  }
}

function getImageInfo(url,success,fail){
  try {
    if (!url) return;
    wx.getImageInfo({
      src: url,
      success(res) {
        if (success) success(res);
      },
      fail:function(res){
        if (fail) fail(res);
      }
    })
  } catch (e) {
    console.error(" wx.getImageInfo API错误");
  }
}

function saveImageToPhotosAlbum(url, success, fail){
  try {
    if (!url) return;
    wx.saveImageToPhotosAlbum({
      filePath:url,
      success(res) {
        if (success) success(res);
      },
      fail: function (res) {
        if (fail) fail(res);
      }
    })
  } catch (e) {
    console.error(" wx.saveImageToPhotosAlbum API错误");
  }
}

/**
 * 保持屏幕常亮
 */
function setKeepScreenOn() {
  try {
    if (wx.setKeepScreenOn) {
      wx.setKeepScreenOn({
        keepScreenOn: true
      });
    }
  } catch (e) {
    console.error(" wx.setKeepScreenOn API错误");
  }
}

/**
 * 设置缓存[同步]
 * @key String 缓存名
 * @value  缓存数据
 */
function setStorageSync(key, value) {
  try {
    wx.setStorageSync(key, value);
  } catch (e) {
    console.error(" wx.setStorageSync API错误");
  }
}

/**
 * 获取缓存[同步]
 * @key String 缓存名
 */
function getStorageSync(key) {
  let sto = null;
  try {
    sto = wx.getStorageSync(key);
  } catch (e) {
    console.error(" wx.getStorageSync API错误");
  }
  return sto;
}

/**
 * 移除缓存[同步]
 * @key String 缓存名
 */
function removeStorageSync(key) {
  try {
    wx.removeStorageSync(key);
  } catch (e) {
    console.error(" wx.removeStorageSync API错误");
  }
}

/**
 * 设置缓存
 * @key String 缓存名
 * @value  缓存数据
 */
function setStorage(key, value) {
  try {
    wx.setStorage({
      key,
      data: value
    })
  } catch (e) {
    console.error(" wx.setStorage API错误");
  }
}

/**
 * 获取缓存
 * @key String 缓存名
 */
function getStorage(key, success, fail) {
  let sto = null;
  try {
    // 是否处理成功
    let isSuccess = false;
    // 是否处理失败
    let isFail = false;
    wx.getStorage({
      key,
      success(res) {
        console.log("success缓存",res)
        if (!isSuccess) {
          isSuccess = true;
          if (success) success(res);
        }
      },
      fail:function(res){
        console.log("fail缓存", res)
        if (!isFail) {
          isFail = true;
          if (fail) fail(res);
        }
      },
      complete:function(res){
        console.log("complete缓存", res)
        if (res.data != undefined && !isSuccess) {
          isSuccess = true;
          if (success) success(res);
        } else if (res.data == undefined && !isFail) {
          isFail = true;
          if (fail) fail(res);
        }
      }
    })
  } catch (e) {
    console.error(" wx.getStorage API错误");
  }
  return sto;
}

/**
 * 移除缓存
 * @key String 缓存名
 */
function removeStorage(key) {
  try {
    wx.removeStorage({
      key,
    })
  } catch (e) {
    console.error(" wx.removeStorage API错误");
  }
}

/**
 * 弹框提示
 * @param msg [提示内容]
 * param dur [提示的延迟时间]
 * param logo [提示图标]
 * param img [提示自定义图标路径]
 */
function showToast(msg, dur, logo, img) {
  var duration = dur || 1500;
  var icon = logo || "none";
  var image = img || false;
  var data = {
    title: msg,
    mask: true,
    duration: duration,
    icon: icon,
  }
  if (image) data.image = image;

  try {
    wx.showToast(data);
  } catch (e) {
    console.error(" wx.showToast API错误");
  }
}

/**
 * 模态框提示
 * @param data Object
 * @param data.content [提示内容]
 * param  data.title  [提示标题]
 * param  data.showCancel [是否显示取消按钮]
 * param  data.cancelText [取消按钮文字]
 * param  data.confirmText  [确定按钮文字]
 * param  data.success()  Function
 */
function showModal(data) {
  try {
    wx.showModal({
      title: data.title || '提示',
      content: data.content || '',
      showCancel: data.showCancel || false,
      cancelText: data.cancelText || "取消",
      cancelColor: data.cancelColor || "#000000",
      confirmText: data.confirmText || "确定",
      confirmColor: data.confirmColor || "#576B95",
      success: function(res) {
        if (res.cancel) {
          if (data.cancel) data.cancel();
        } else if (res.confirm) {
          if (data.confirm) data.confirm();
        }
      },
      fail: function(res) {
        if (res && res.errMsg == "fail cancel") {
          if (data.cancel) data.cancel();
        } else {
          if (data.fail) data.fail();
        }
      },
      complete: function() {
        if (data.complete) data.complete();
      }
    })
  } catch (e) {
    console.error(" wx.showModal API错误");
  }
}

/**
 * 微信扫码
 * @param data Object
 */
function scanCode(data) {
  try {
    wx.scanCode({
      onlyFromCamera: data.onlyFromCamera || false,
      scanType: data.scanType || ['barCode', 'qrCode'],
      success: function(res) {
        if (data.success) data.success(res);
      },
      fail: function() {
        if (data.fail) data.fail();
      },
      complete: function() {
        if (data.complete) data.complete();
      }
    })
  } catch (e) {
    console.error(" wx.scanCode API错误");
  }
}

function login(data) {
  try {
    console.warn('wx.login API开始请求');
    wx.login({
      success(res) {
        if (data.success) data.success(res);
      },
      fail: function(res) {
        if (data.fail) data.fail(res);
      },
      complete: function(res) {
        console.warn('wx.login API完成',res);
        if (data.complete) data.complete(res);
      }
    })
  } catch (e) {
    console.error(" wx.login API错误");
  }
}

function getUserInfo(data){
  try {
    console.warn('wx.getUserInfo API开始请求');
    wx.getUserInfo({
      success(res) {
        if (data.success) data.success(res);
      },
      fail: function (res) {
        if (data.fail) data.fail(res);
      },
      complete: function (res) {
        console.warn('wx.getUserInfo API完成', res);
        if (data.complete) data.complete(res);
      }
    })
  } catch (e) {
    console.error(" wx.getUserInfo API错误");
  }
}

function getLocation(data) {
  try {
    // 是否处理成功
    let isSuccess = false;
    // 是否处理失败
    let isFail = false;
    console.warn('wx.getLocation API开始请求');
    wx.getLocation({
      type:data.type || 'gcj02',
      success(res) {
        if (!isSuccess) {
          isSuccess = true;
          if (data.success) data.success(res);
        }
      },
      fail: function(res) {
        if (!isFail) {
          isFail = true;
          if (data.fail) data.fail(res);
        }
      },
      complete: function(res) {
        console.warn('wx.getLocation API完成', res);
        if (res.latitude != undefined && !isSuccess) {
          isSuccess = true;
          if (data.success) data.success(res);
        } else if (res.latitude == undefined && !isFail) {
          isFail = true;
          if (data.fail) data.fail(res);
        }
        if (data.complete) data.complete(res);
      }
    })
  } catch (e) {
    console.error(" wx.getLocation API错误");
  }
}

function openSetting(data) {
  try {
    wx.openSetting({
      success(res) {
        if (data.success) data.success(res);
      },
      fail: function(res) {
        if (data.fail) data.fail(res);
      },
      complete: function(res) {
        if (data.complete) data.complete(res);
      }
    })
  } catch (e) {
    console.error(" wx.openSetting API错误");
  }
}

/**
 * 手机号正则校验
 * params phone 手机号
 */
function checkPhone(phone) {
  var myreg = /^[1][2,3,4,5,6,7,8][0-9]{9}$/;
  if (!myreg.test(phone)) {
    return false;
  } else {
    return true;
  }
}

/**
 * 获取年月日
 * params num 与当天时间的差值
 * params tempDate 直接设置日期
 */
function time(num, tempDate) {
  var n = num || 0;
  var that = this;
  var date;

  if (tempDate) {
    date = new Date(tempDate);
  } else {
    date = new Date();
  }

  date.setDate(date.getDate() + n);
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var day = date.getDate();
  var week = date.getDay();
  var hour = date.getHours();
  var minute = date.getMinutes();
  var second = date.getSeconds();
  var msec = date.getTime();
  if (month < 10) {
    month = '0' + month;
  }
  if (day < 10) {
    day = '0' + day;
  }
  if (minute < 10) {
    minute = '0' + minute;
  }

  var typeA = month + '月' + day + '日';
  var typeB = year + '-' + month + '-' + day;
  var typeC = hour + ':' + minute + ":" + second;
  var typeD = typeB + " " + typeC;

  return {
    typeA: typeA,
    typeB: typeB,
    typeC: typeC,
    typeD: typeD,
    year: year,
    month: month,
    day: day,
    week: week,
    hour: hour,
    minute: minute,
    msec: msec, //毫秒
    dayMsec: 1000 * 60 * 60 * 24, //一天的毫秒
  };
}